package logic.algorithm.aco;

import java.util.ArrayList;
import javax.swing.JFrame;
import logic.objects.Connection;
import logic.objects.Problem;
import logic.service.PheromonService;

public class RankBasedAS extends AntSystem {

	double w;

	@Override
	protected void initializeParameters() {
		beta = 5.0;
		alpha = 1.0;
		roh = 0.1;
		w = 6.0;
		tau0 = (0.5 * w * (w - 1))
				/ (roh * PheromonService
						.getNearestNeighborShortedTourValue(problem));

	}

	public RankBasedAS(Problem problem, JFrame frame) {
		super(problem, frame);
	}

	@Override
	protected void updatePheromon() {
		for (int i = 0; i < problem.getConnections().getSizeX(); i++) {
			for (int j = 0; j < problem.getConnections().getSizeY(); j++) {
				if (i != j) {
					Connection con = problem.getConnections().get(i, j);
					con.setPheromon(con.getPheromon() * (1.0 - roh));
				}
			}
		}
		ArrayList<Ant> bestAnts = getBestSolutionAnts();

		for (int j = 0; j < w; j++) {
			updatePheromonByAnt(bestAnts.get(j), (w - j) * 1.0);
		}
		problem.getConnections().updateMaxPheromon();
	}

	private ArrayList<Ant> getBestSolutionAnts() {
		ArrayList<Ant> resultSet = new ArrayList<Ant>();
		for (int i = 0; i < w; i++) {
			int minIndex = 0;
			double length = Double.MAX_VALUE;
			for (int j = 0; j < ants.size(); j++) {
				if (length > ants.get(i).getTourLength()
						&& !resultSet.contains(ants.get(i))) {
					length = ants.get(i).getTourLength();
					minIndex = j;
				}
			}
			resultSet.add(ants.get(minIndex));
		}
		return resultSet;

	}
}